<template>
  <view class="charging-rule-wait-page page-content">
    <z-paging ref="paging" v-model="currentList" @query="queryList" :auto="false" :refresher-enabled="true"
      :loading-more-enabled="true" empty-view-text="暂无数据">
      <template #top>
        <up-navbar title="计费规则审核" :autoBack="false" :fixed="true" bgColor="transparent" :border="false" placeholder
          @leftClick="handleBackClick">
          <template>
            <view></view>
          </template>
        </up-navbar>

        <up-sticky class="padding-20" bgColor="transparent">
          <!-- <up-search :clearabled="true" :showAction="false" placeholder="请输入姓名、账号"></up-search> -->
          <up-tabs :list="tabsList" :scrollable="false" @change="handleTabChange"></up-tabs>
        </up-sticky>
      </template>

      <view class="charging-rule-wait-list">
        <view class="list-item-card" v-for="(item, index) in currentList" :key="index">
          <view class="card-header">
            <view class="title">
              审核ID：<text class="number">{{ item.bizCode }}</text>
            </view>
          </view>
          <view class="card-content-box">
            <view class="content">
              <view class="item">
                <text class="label">
                  计费规则名称：
                </text>
                <text class="value">
                  {{ item.name }}
                </text>
              </view>
              <view class="item">
                <text class="label">
                  提交人：
                </text>
                <text class="value">
                  {{ item.operateName }}
                </text>
              </view>
              <view class="item">
                <text class="label">
                  提交时间：
                </text>
                <text class="value">
                  {{ item.createTime }}
                </text>
              </view>
              <view class="item">
                <text class="label">
                  变更类型：
                </text>
                <text class="value">
                  {{ getUpdateTypeText(item.updateType) }}
                </text>
              </view>
              <view class="item">
                <text class="label">
                  场地名称：
                </text>
                <text class="value">
                  {{ item.veName }}
                </text>
              </view>
              <view class="item" v-if="item.auditContent">
                <text class="label">
                  审核内容：
                </text>
                <text class="value">
                  {{ item.auditContent }}
                </text>
              </view>
            </view>
            <view class="card-footer">
              <view class="checkbox-box">
              </view>
              <view class="operate" v-if="currentTab === 0">
                <!-- 待审核状态显示操作按钮 -->
                <up-button type="primary" text="通过审核" class="custom-style" @click="handlePass(item)"></up-button>
                <up-button type="error" text="拒绝审核" class="custom-style" @click="handleRefuse(item)"></up-button>
              </view>
              <view class="audit-result" v-else>
                <!-- 已审核状态显示审核结果 -->
                <view class="result-item">
                  <text class="result-label">审核状态：</text>
                  <text :class="['result-value', getStatusClass(item.status)]">{{ getStatusText(item.status) }}</text>
                </view>
                <view class="result-item" v-if="item.auditUserName">
                  <text class="result-label">审核人：</text>
                  <text class="result-value">{{ item.auditUserName }}</text>
                </view>
                <view class="result-item" v-if="item.updateTime">
                  <text class="result-label">审核时间：</text>
                  <text class="result-value">{{ item.updateTime }}</text>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </z-paging>

    <!-- 审核通过弹窗 -->
    <up-modal :show="showApproveModal" title="审核通过" :showCancelButton="true" confirmText="确认通过"
      @confirm="handleApproveConfirm" @cancel="handleApproveCancel">
      <view class="modal-content">
        <view class="user-info">
          <text class="info-text">确定要通过 {{ currentItem?.name }} 的计费规则审核吗？</text>
        </view>
        <view class="form-item">
          <text class="label">审核备注：</text>
          <up-textarea v-model="approveForm.remark" placeholder="请输入审核备注（可选）" :maxlength="200" count
            showWordLimit></up-textarea>
        </view>
      </view>
    </up-modal>

    <!-- 审核驳回弹窗 -->
    <up-modal :show="showRejectModal" title="审核驳回" :showCancelButton="true" confirmText="确认驳回"
      @confirm="handleRejectConfirm" @cancel="handleRejectCancel">
      <view class="modal-content">
        <view class="user-info">
          <text class="info-text">确定要驳回 {{ currentItem?.name }} 的计费规则审核吗？</text>
        </view>
        <view class="form-item">
          <text class="label">驳回原因：<text class="required">*</text></text>
          <up-textarea v-model="rejectForm.remark" placeholder="请输入驳回原因" :maxlength="200" count
            showWordLimit></up-textarea>
        </view>
      </view>
    </up-modal>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { getChargingRuleWaitList, authorMoneyCountLog } from '@/api';

const currentTab = ref(0);
const tabsList = ref([
  {
    name: '待审核',
    value: '1',
  },
  {
    name: '已审核',
    value: '2',
  },
])

// z-paging 组件引用
const paging = ref(null)

// 当前显示的列表数据
const currentList = ref([])

// 审核弹窗相关
const showApproveModal = ref(false)
const showRejectModal = ref(false)
const currentItem = ref(null)
const approveForm = ref({
  remark: ''
})
const rejectForm = ref({
  remark: ''
})

// 处理返回点击事件
const handleBackClick = () => {
  uni.redirectTo({
    url: '/pages/home/index'
  })
}

const handlePass = (item) => {
  currentItem.value = item
  approveForm.value.remark = ''
  showApproveModal.value = true
}

const handleApproveConfirm = () => {
  // 确认通过审核
  showApproveModal.value = false

  // 调用审核通过接口
  uni.showLoading({ title: '处理中...' })

  // 调用审核接口
  authorMoneyCountLog({
    bizCode: currentItem.value.bizCode, // 审核ID
    author: 0, // 0表示审核通过
    dealRemark: approveForm.value.remark // 审核备注
  }).then(res => {
    uni.hideLoading()
    if (res.success === true) {
      uni.showToast({
        title: '审核已通过',
        icon: 'success'
      })
      // 刷新列表
      if (paging.value) {
        paging.value.reload()
      }
    } else {
      uni.showToast({
        title: res.msg || '操作失败',
        icon: 'none'
      })
    }
  }).catch(() => {
    uni.hideLoading()
    uni.showToast({
      title: '网络异常，请稍后重试',
      icon: 'none'
    })
  })
}

const handleApproveCancel = () => {
  showApproveModal.value = false
}

const handleRefuse = (item) => {
  currentItem.value = item
  rejectForm.value.remark = ''
  showRejectModal.value = true
}

const handleRejectConfirm = () => {
  // 验证是否填写了驳回原因
  if (!rejectForm.value.remark) {
    uni.showToast({
      title: '请填写驳回原因',
      icon: 'none'
    })
    return
  }

  // 确认拒绝审核
  showRejectModal.value = false

  // 调用拒绝审核接口
  uni.showLoading({ title: '处理中...' })

  // 调用审核接口
  authorMoneyCountLog({
    bizCode: currentItem.value.bizCode, // 审核ID
    author: 1, // 1表示拒绝审核
    dealRemark: rejectForm.value.remark // 审核备注/驳回原因
  }).then(res => {
    uni.hideLoading()
    if (res.success === true) {
      uni.showToast({
        title: '已驳回审核',
        icon: 'success'
      })
      // 刷新列表
      if (paging.value) {
        paging.value.reload()
      }
    } else {
      uni.showToast({
        title: res.msg || '操作失败',
        icon: 'none'
      })
    }
  }).catch(() => {
    uni.hideLoading()
    uni.showToast({
      title: '网络异常，请稍后重试',
      icon: 'none'
    })
  })
}

const handleRejectCancel = () => {
  showRejectModal.value = false
}

// 获取变更类型文本
const getUpdateTypeText = (updateType) => {
  const typeMap = {
    1: '新增规则内容',
    2: '修改规则内容',
    3: '删除停车场',
    4: '新增停车场'
  }
  return typeMap[updateType] || '未知类型'
}

// 获取审核状态文本
const getStatusText = (status) => {
  const statusMap = {
    1: '待审核',
    2: '审核通过',
    3: '审核驳回'
  }
  return statusMap[status] || '未知状态'
}

// 获取审核状态样式类
const getStatusClass = (status) => {
  const classMap = {
    1: 'status-pending',
    2: 'status-approved',
    3: 'status-rejected'
  }
  return classMap[status] || 'status-default'
}

// 获取车辆列表数据
const queryList = async (pageNo, pageSize) => {
  console.log(pageNo, pageSize)

  const params = {
    pageNum: pageNo,
    pageSize,
    status: currentTab.value === 0 ? "1" : "2,3" // 1.待审核 2.审核通过 3.审核驳回
  }

  await fetchList(params)
};

const fetchList = async (params) => {
  try {
    const result: any = await getChargingRuleWaitList(params)
    const data = result.data
    paging.value.complete(data.records || [])
  } catch (error) {
    paging.value.complete(false)
  }
}

// 选项卡切换事件
const handleTabChange = (e) => {
  const newIndex = e.index;
  if (currentTab.value === newIndex) {
    return; // 如果是同一个tab，不需要重新加载
  }

  currentTab.value = newIndex;

  // 切换tab时重新加载数据
  if (paging.value) {
    paging.value.reload();
  }
};

// 页面挂载时获取数据
onMounted(() => {
  // 页面挂载时初始化数据
  if (paging.value) {
    paging.value.reload();
  } else {
    fetchList({
      pageNum: 1,
      pageSize: 10,
      status: "1" // 默认显示待审核状态
    })
  }
});
</script>

<style scoped>
.charging-rule-wait-list {
  padding: 20px;
}

.search-bar {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.audit-result {
  padding: 10px 0;
}

.result-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.result-label {
  font-size: 14px;
  color: #666;
  margin-right: 8px;
  min-width: 80px;
}

.result-value {
  font-size: 14px;
  color: #333;
}

.status-pending {
  color: #ff9500;
}

.status-approved {
  color: #07c160;
}

.status-rejected {
  color: #fa5151;
}

.status-default {
  color: #999;
}

/* 弹窗样式 */
.modal-content {
  padding: 10px;
}

.user-info {
  margin-bottom: 15px;
}

.info-text {
  font-size: 14px;
  color: #333;
}

.form-item {
  margin-bottom: 10px;
}

.form-item .label {
  display: block;
  margin-bottom: 5px;
  font-size: 14px;
  color: #333;
}

.form-item .required {
  color: #f56c6c;
}
</style>